import React, { Component } from 'react';
import context from "../uilt/context"
import { withRouter } from 'react-router-dom';
class Catelist extends Component {
    state = {
        catelist: []
    }
    componentDidMount() {
        // 注册事件（绑定事件）
        context.addListener("cate", (list) => {
            this.setState({
                catelist: list
            })
        })
        // 注册点击事件传值
        context.addListener("save", (index) => {
            let goodslist = []
            if (index === 3) {
                goodslist = this.state.catelist && this.state.catelist.sort((a, b) => {
                    return b.salesPrice.value - a.salesPrice.value
                })
                this.setState({
                    catelist: goodslist
                })
            } else {

            }

        })
    }
    componentWillUnmount() {
        context.removeListener("save", (index) => {
        })
        context.removeListener("cate", (list) => {

        })
    }
    hangclick(id) {
        this.props.history.push("/details/" + id)
    }
    render() {
        return (
            <div className='catelist'>
                {
                    // 解决初次渲染报错而无法执行后面代码，异步操作问题
                    this.state.catelist && this.state.catelist.length > 0 && this.state.catelist.map((item, index) => {
                        return (
                            <div className="list" key={index} onClick={() => { this.hangclick(item.id) }}>
                                <img src={item.pic} alt="" />
                                <div className="name">{item.name}</div>
                                <div className="pirce">{item.pice}</div>
                                <span>￥{item.salesPrice.value}</span>
                            </div>
                        )
                    })
                }
            </div>
        );
    }
}

export default withRouter(Catelist);